package com.zhoukx.singleton.type5;

/**
 * @ClassName SingletonTest03
 * @Description: 懒汉式  线程安全  双端检索
 * @Author zhoukx
 * @Date 2020/8/6
 **/
public class SingletonTest05 {
    public static void main(String[] args) {
        System.out.println("双重检查");
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance:" + instance.hashCode());
        System.out.println("instance2:" + instance2.hashCode());
    }
}

//  解决线程安全问题
class Singleton {

    private static volatile Singleton instance;

    private Singleton() {

    }



     // 双重检索模式
    // 提供一个静态的公有方法，当使用该方法，才去创建，解决线程安全和懒加载问题
    public static synchronized Singleton getInstance() {

        if (instance == null) {
            synchronized (Singleton.class){
                if (instance == null){
                    instance = new Singleton();
                }
            }

        }
        return instance;
    }
}
